package com.mainbo.modular.system.controller;

import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.mainbo.core.common.annotion.BussinessLog;
import com.mainbo.core.common.constant.ApolloConstants;
import com.mainbo.core.common.constant.Const;
import com.mainbo.core.common.constant.dictmap.MenuDict;
import com.mainbo.core.common.constant.dictmap.UserDict;
import com.mainbo.core.common.exception.BizExceptionEnum;
import com.mainbo.core.shiro.SessionKey;
import com.mainbo.core.shiro.ShiroKit;
import com.mainbo.core.shiro.service.UserAuthService;
import com.mainbo.core.util.Result;
import com.mainbo.core.util.StringUtil;
import com.mainbo.core.util.WebThreadLocalUtils;
import com.mainbo.modular.excel.BatchImportService;
import com.mainbo.modular.jms.MessageTypes;
import com.mainbo.modular.system.model.*;
import cn.stylefeng.roses.core.base.controller.BaseController;
import com.mainbo.modular.system.model.meta.MetaUtils;
import com.mainbo.modular.system.model.meta.vo.Meta;
import com.mainbo.modular.system.service.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import com.mainbo.core.log.LogObjectHolder;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 控制器
 *
 * @author moshang
 * @Date 2020-02-13 21:23:57
 */
@Controller
@RequestMapping("/ptAccount")
public class PtAccountController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(PtAccountController.class);

    private String PREFIX = "/system/ptAccount/";

    @Resource
    private IPtAccountService ptAccountService;
    @Resource
    private IPtOrgService orgService;
    @Resource
    private IPtAreaService areaService;
    @Resource
    private BatchImportService batchImportService;
     @Resource
     private UserAuthService userAuthService;
     @Resource
     private IPtUserRoleService ptUserRoleService;
     @Resource
     private IPtRoleService ptRoleService;
    /**
     * 跳转到首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "ptAccount.html";
    }

    /**
     * 跳转到添加
     */
    @RequestMapping("/ptAccount_add")
    public String ptAccountAdd() {
        return PREFIX + "ptAccount_add.html";
    }

    /**
     * 跳转到修改
     */
    @RequestMapping("/ptAccount_update/{ptAccountId}")
    public String ptAccountUpdate(@PathVariable Integer ptAccountId, Model model) {
        PtAccount ptAccount = ptAccountService.selectById(ptAccountId);
        model.addAttribute("item", ptAccount);
        LogObjectHolder.me().set(ptAccount);
        return PREFIX + "ptAccount_edit.html";
    }

    /**
     * 获取列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String condition) {
        return ptAccountService.selectList(null);
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(PtAccount ptAccount) {
        ptAccountService.insert(ptAccount);
        return SUCCESS_TIP;
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer ptAccountId) {
        ptAccountService.deleteById(ptAccountId);
        return SUCCESS_TIP;
    }


    /**
     * 详情
     */
    @RequestMapping(value = "/detail/{ptAccountId}")
    @ResponseBody
    public Object detail(@PathVariable("ptAccountId") Integer ptAccountId) {
        return ptAccountService.selectById(ptAccountId);
    }
    /**
     * 跳转到查看用户详情页面
     */
    @RequestMapping("/user_info")
    public String userInfo(Model model) {
        PtAccount current=ShiroKit.getSessionAttr(SessionKey.CURRENT_USER);
        String account = Objects.requireNonNull(current).getAccount();
        if (ToolUtil.isEmpty(account)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        PtAccount user = this.userAuthService.user(account);
        model.addAttribute("user",user);
        model.addAttribute("storageUrl", ApolloConstants.readStorageUrl());
        model.addAttribute("uploadUrl", ApolloConstants.readUploadUrl());
        return PREFIX + "user_view.html";
    }

    /**
     * 跳转到修改密码界面
     */
    @RequestMapping("/user_chpwd")
    public String chPwd() {
        return PREFIX + "user_chpwd.html";
    }
    /**
     * 修改
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Result update(PtAccount ptAccount) {
        return ptAccountService.updateByUserType(ptAccount);
    }

    @RequestMapping("/batch/add")
    public String toBatchInsert(Model m, UserSearchModel usm, HttpServletRequest request) {
        PtOrg org = orgService.selectById(usm.getOrgId());
        List<Meta> phaseList = MetaUtils.getOrgTypeProvider().listAllPhase(org.getSchoolings());
        m.addAttribute("phaseList", phaseList);
        String orgStr = org.getName();
        PtArea area1 = areaService.selectById(org.getAreaId());
        if (area1.getPid() != 0) {
            PtArea area2 = areaService.selectById(area1.getPid());
            orgStr = area2.getAreaName() + area1.getAreaName() + orgStr;
        } else {
            orgStr = area1.getAreaName() + orgStr;
        }

        m.addAttribute("orgName", orgStr);
        m.addAttribute("model", usm);
        m.addAttribute("prefix", WebThreadLocalUtils.getPrefixUrl(request));
        return PREFIX + "batchAdd.html";
    }


    /**
     * 下载批量注册模板
     *
     * @param phaseId 学段id
     * @param orgId   机构id
     */
    @RequestMapping("/downLoadRegisterTemplate")
    public void downLoadRegisterTemplate(Integer phaseId, String orgId, Integer templateType,
                                         HttpServletResponse response) {
        try {
            batchImportService.getRegisterTemplate(templateType, phaseId, orgId, response);
        } catch (Exception e) {
            logger.error("下载批量注册模板出错", e);
        }
    }

    /**
     * 批量注册
     *
     * @param orgId   机构id
     * @param phaseId 学段id
     * @param file    文件流
     */
    @RequestMapping(value = "/batchRegister")
    @BussinessLog(value = "批量注册", key = "account", dict = UserDict.class)
    @ResponseBody
    public Result batchRegister(Integer userType, String orgId, Integer phaseId, MultipartFile file, HttpServletResponse response) {
        Result rs = new Result();
        InputStream is = null;
        rs.setData(userType);
        try {
            StringBuilder resultBuffer = null;
            if (PtAccount.AREA_USER == userType) { // 区域用户注册
                logger.info("区域用户管理——批量注册用户，学校id：{}", orgId);
            } else if (PtAccount.TEACHER_USER == userType) { // 教师用户注册
                logger.info("教师用户管理——批量注册用户，机构id：{}", orgId);
            } else if (PtAccount.STUDENT_USER == userType) { // 学生用户注册
                logger.info("学生用户管理——批量注册用户，机构id：{}", orgId);
            } else if (PtAccount.PARENTS_USER == userType) { // 家长用户注册
                logger.info("家长用户管理——批量注册用户，机构id：{}", orgId);
            }
            resultBuffer = batchImportService.batchRegiterUser(userType, orgId, phaseId, file);
            rs.setCode(Result.SUCCESS);
            rs.setMsg(resultBuffer.toString());
            response.setContentType("text/html;charset=utf-8");
        } catch (Exception e) {
            rs.setCode(Result.FAIL);
            rs.setMsg("批量注册出错！");
            logger.error("批量注册出错", e);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    logger.error("", e);
                }
            }
        }
        return rs;
    }

    /**
     * 更改账号密码
     *
     * @param accountIds 用户id
     * @return 返回
     */
    @RequestMapping(value = "/updatePwds")
    @ResponseBody
    public Result updatePwds(String accountIds) {
        Result result = new Result();
        try {
            if (StringUtils.isNotEmpty(accountIds)) {
                String[] ids = accountIds.split(",");
                for (String accountId : ids) {
                    ptAccountService.resetPassword(accountId);
                    logger.info("用户管理", "用户管理——重置密码为{}，用户ID：{}",

                            Const.DEFAULT_PWD, accountId);
                    ptAccountService.sendAccountModifyMessage(accountId);
                }
            }
            result.setCode(Result.SUCCESS);
            result.setMsg("密码重置成功，新密码为:" + Const.DEFAULT_PWD);
            logger.info("保存成功");
        } catch (Exception e) {
            result.setCode(Result.FAIL);
            logger.info("保存失败", e);
            result.setMsg("操作失败");
        }
        return result;
    }
    /**
     * 重置密码
     *
     * @param accountId 用户id
     * @return 返回
     */
    @RequestMapping(value = "/resetPwd")
    @ResponseBody
    public Result resetPwd(String accountId) {
        Result result = new Result();
        try {
                    ptAccountService.resetPassword(accountId);
                    logger.info("用户管理", "用户管理——重置密码为{}，用户ID：{}",
                            Const.DEFAULT_PWD, accountId);
                    ptAccountService.sendAccountModifyMessage(accountId);
            result.setCode(Result.SUCCESS);
            result.setMsg("密码重置成功，新密码为:" + Const.DEFAULT_PWD);
            logger.info("保存成功");
        } catch (Exception e) {
            result.setCode(Result.FAIL);
            logger.info("保存失败", e);
            result.setMsg("操作失败");
        }
        return result;
    }

    /**
     * 修改密码
     *
     * @param login 账号信息
     * @param m     数据模型
     * @return 返回
     */

    @RequestMapping(value = "/changePwd", method = RequestMethod.POST)
    @BussinessLog(value = "修改个人密码", key = "name")
    @ResponseBody
    public Result changePwd(PtAccount login, Model m) {
        LogObjectHolder.me().set(login);
        return ptAccountService.updatePwd(login);

    }

    /**
     * 账号状态更新
     *
     * @param account
     *          账号信息
     * @return 返回
     */
    @RequestMapping("/updateEnable")
    @ResponseBody
    public Result updateEnable(PtAccount account) {
        Result result = new Result();
        try {
            ptAccountService.updateEnable(account);
            if (account.getEnable()) {
                result.setMsg("解禁成功");
            } else {
                result.setMsg("禁用成功");
            }
        } catch (Exception e) {
            logger.debug("禁用失败-{}", e);
            if (account.getEnable()) {
                result.setMsg("解禁失败");
            } else {
                result.setMsg("禁用失败");
            }
        }
        return result;
    }

    /**
     * 批量冻结
     *
     * @param accountIds
     *          要冻结的id
     * @return JuiResult
     */
    @RequestMapping("/batchDisableAccount")
    @ResponseBody
    public Result batchDisableAccount(String accountIds) {
        Result result = new Result();
        result.setCode(Result.SUCCESS);
        try {
            if (!StringUtils.isEmpty(accountIds)) {
                for (String id : accountIds.split(",")) {
                    PtAccount account=ptAccountService.selectById(id);
                    account.setEnable(false);
                    ptAccountService.updateEnable(account);

                }
            }
            result.setMsg("批量冻结成功");
            logger.info("批量冻结成功");
        } catch (Exception e) {
            logger.info("批量冻结失败", e);
            result.setCode(Result.FAIL);
            result.setMsg("批量冻结失败");
        }
        return result;
    }
    /**
     * 批量解冻
     *
     * @param accountIds
     *          要解冻的id
     * @return JuiResult
     */
    @RequestMapping("/batchUpdateEnable")
    @ResponseBody
    public Result batchUpdateEnable(String accountIds) {
        Result result = new Result();
        result.setCode(Result.SUCCESS);
        try {
            if (!StringUtils.isEmpty(accountIds)) {
                for (String id : accountIds.split(",")) {
                    PtAccount account=ptAccountService.selectById(id);
                    account.setEnable(true);
                    ptAccountService.updateEnable(account);

                }
            }
            result.setMsg("批量启用成功");
            logger.info("批量启用成功");
        } catch (Exception e) {
            result.setCode(Result.FAIL);
            logger.info("批量启用失败", e);
            result.setMsg("批量启用失败");
        }
        return result;
    }

    @RequestMapping("/toPostManage")
    public String toPostManage(Model model, PtUserRole us) {
        if (StringUtils.isNotEmpty(us.getAccountId())) {
            model.addAttribute("userType", ptAccountService.selectById(us.getAccountId()).getUserType());
        }
        model.addAttribute("accountId", us.getAccountId());
        return "/system/postmanage/index.html";
    }
    @RequestMapping("/findPostManage")
    @ResponseBody
    public List<PtUserRole> toPostManage( String accountId) {
        EntityWrapper<PtUserRole> wrapper=new EntityWrapper<>();
        wrapper.eq("account_id",accountId);
        List<PtUserRole> usList = ptUserRoleService.selectList(wrapper);
        for (PtUserRole u : usList) {
            PtRole role = ptRoleService.selectById(u.getRoleId());
            if (role == null) {
                usList.remove(u);
            }else {
                u.setRoleName(role.getRoleName());
            }
            if (u.getPhaseId()!=null){
                Meta meta=MetaUtils.getMeta(u.getPhaseId());
                if (meta!=null){
                    u.setPhaseName(meta.getName());
                }
            }
            if (u.getSubjectId()!=null){
                Meta meta=MetaUtils.getMeta(u.getSubjectId());
                if (meta!=null){
                    u.setSubjectName(meta.getName());
                }
            }
            if (u.getGradeId()!=null){
                Meta meta=MetaUtils.getMeta(u.getGradeId());
                if (meta!=null){
                    u.setGradeName(meta.getName());
                }
            }
        }
        return usList;
    }
    /**
     * 增加用户职务
     *
     * @param model
     *          数据模型
     * @param accountId
     *          用户id
     * @param spaceId
     *          空间id
     * @return 返回
     */
    @RequestMapping("/addOrEditPostManage")
    public String addOrEditPostManage(Model model, String accountId, String spaceId) {
        ptUserRoleService.addOrEditPostManage(accountId, spaceId, model);
        if (StringUtils.isBlank(spaceId)) {
            return "/system/postmanage/add.html";
        }else {
            return "/system/postmanage/editClass.html";
        }
    }

    @RequestMapping("/showInfoBySysRoleId")
    @ResponseBody
    public Object showInfoBySysRoleId( Integer roleId) {
        Map<String, Boolean> dataMap = new HashMap<String, Boolean>();
        if (roleId != null) {
            PtRole role = ptRoleService.selectById(roleId);
            if (role != null) {
                dataMap.put("showSubject", role.getShowSubject());
                dataMap.put("showGrade", role.getShowGrade());
                dataMap.put("showPhase", role.getShowPhase());
            }
        }
        return dataMap;
    }

    /**
     * 保存用户职务、角色
     */
    @RequestMapping(value = "/saveAreaPostManage")
    @ResponseBody
    public Result saveAreaPostManage(PtUserRole us) {
        Result result = new Result();
        try {
            result = ptUserRoleService.saveAreaPostManage(us, result);
            logger.info("保存成功");
        } catch (Exception e) {
            logger.error(e.getMessage());
            logger.info("保存失败", e);
            result.setMsg("操作失败");
        }
        return result;
    }


    /**
     * 删除用户职务
     *          数据模型
     * @param id
     *          用户id
     * @return 返回
     */
    @RequestMapping("/deleteUserPost")
    @ResponseBody
    public Result deleteUserPost( String id) {
        Result result = new Result();
        try {
            if (StringUtils.isNotEmpty(id)) {
                PtUserRole urRole = ptUserRoleService.selectById(id);

                PtUserRole userRole = new PtUserRole();
                userRole.setId(id);
                userRole.setAccountId(urRole.getAccountId());
                userRole.setOrgId(urRole.getOrgId());
                ptAccountService.sendUserRoleMessege(MessageTypes.USER_ROLE_DELETE.name(), userRole);
                ptUserRoleService.deleteById(id);
                result.setMsg("删除成功");
                result.setCode(Result.SUCCESS);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            result.setCode(Result.FAIL);
            logger.info("删除失败");
            result.setMsg("删除失败");
        }
        return result;
    }

    /**
     * 禁用用户职务

     *          数据模型
     * @param ur
     *          用户角色
     * @return 返回
     */
    @RequestMapping("/disabledUserPost")
    @ResponseBody
    public Result disabledUserPost(PtUserRole ur) {
        Result result = new Result();
        try {
            if (ur.getEnable()) {
                result.setMsg("职务已启用");
            } else {
                result.setMsg("职务已被禁用");
            }
            ptUserRoleService.updateById(ur);
            ptAccountService.sendUserRoleMessege(MessageTypes.USER_ROLE_UPDATE.name(), ptUserRoleService.selectById(ur.getId()));
            result.setCode(Result.SUCCESS);
        } catch (Exception e) {
            logger.error(e.getMessage());
            result.setCode(Result.FAIL);
            result.setMsg("操作失败");
        }
        return result;
    }
}
